package com.example.bookservice.kafka;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.bookservice.entity.Book;
import com.example.bookservice.service.BookService;
import com.example.commom.enums.StatusCodeEnum;
import com.example.commom.exception.CustomException;
import com.example.commom.global.KafkaConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户更新用户名, 其书籍应该也要同步更新.
 */
@Slf4j
@Configuration
@Transactional
public class KafkaUpdateBookInfoReceiver {


    @Autowired
    private BookService bookService;


    @KafkaListener(topics = KafkaConstants.KAFKA_UPDATE_BOOK_INFO, groupId = KafkaConstants.KAFKA_GROUP_ID)
    public void receiveComment(String message, Acknowledgment acknowledgment) {

        try {

            log.info("收到消息: " + message);

            String[] strings = message.split(":");

            // 拿到旧的 用户名
            String oldUserName = strings[0];
            // 拿到新的 用户名
            String newUserName = strings[1];

            // 进行更新操作
            LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Book::getAuthor, oldUserName)
                    .set(Book::getAuthor, newUserName);

            boolean success = bookService.update(updateWrapper);
            if (success) {
                log.info(LocalDateTime.now() + ": 用户" + oldUserName + " 的书籍作者已更新为: " + newUserName);
                acknowledgment.acknowledge();
            } else {
                throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new CustomException(StatusCodeEnum.FAILED.getMsg(), StatusCodeEnum.FAILED.getCode());
        }

    }
}
